package top.hjc.orange.repository.config;

import jakarta.persistence.EntityManager;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.jdbc.core.JdbcTemplate;
import top.hjc.orange.repository.support.OrangeJpaRepositoryImpl;

import java.io.Serializable;

/**
 * @author: huangjicheng
 * @date: 2025/10/10
 * @desc：
 */
public class CustomJpaRepositoryFactory extends JpaRepositoryFactory {

    private final JdbcTemplate jdbcTemplate;

    public CustomJpaRepositoryFactory(EntityManager entityManager, JdbcTemplate jdbcTemplate) {
        super(entityManager);
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    protected JpaRepositoryImplementation<?, ?> getTargetRepository(
            RepositoryInformation information, EntityManager entityManager) {

        JpaEntityInformation<?, Serializable> entityInformation =
                getEntityInformation(information.getDomainType());

        Object repository = getTargetRepositoryViaReflection(
                information,
                entityInformation,
                entityManager,
                jdbcTemplate
        );

        return (JpaRepositoryImplementation<?, ?>) repository;
    }

    @Override
    protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
        return OrangeJpaRepositoryImpl.class;
    }
}
